package com.lgy.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.CountDownLatch;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 下载线程，从远程文件下载到本地，需要制定本地地址
 * @author fengchao
 *
 */
public class DownloadThread extends Thread {
	private static Logger logger = LoggerFactory.getLogger(DownloadThread.class);
	/**
	 * 文件的远程地址
	 */
	private String url;
	/**
	 * 文件存放的地址由path+fileName组成
	 */
	private String localPath;
	/**
	 * 文件的起始偏移量
	 */
	private Long offset;

	/**
	 * 分配给本线程的下载字节数
	 */
	private Long length;
	/**
	 * httpClient客户端
	 */
	private CloseableHttpClient httpClient;

	private HttpContext httpContext;
	
	private CountDownLatch end;
	
	public DownloadThread(String url, String localPath, Long offset, Long length, CloseableHttpClient httpClient,
							CountDownLatch end) {
		this.url = url;
		this.localPath = localPath;
		this.offset = offset;
		this.length = length;
		this.httpClient = httpClient;
		this.httpContext =  new BasicHttpContext();
		this.end = end;
	}
	
	@Override
	public void run() {
		HttpGet httpGet = new HttpGet(this.url);
		httpGet.addHeader("Range", "bytes=" + this.offset + "-" + (this.offset + this.length - 1));
		CloseableHttpResponse response;
		try {
			response = httpClient.execute(httpGet, httpContext);
			BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
			byte[] buff = new byte[1024];
			int bytesRead;
			File newFile = new File(localPath);
			RandomAccessFile raf = new RandomAccessFile(newFile, "rw");
			while ((bytesRead = bis.read(buff, 0, buff.length)) != -1) {
				raf.seek(this.offset);
				raf.write(buff, 0, bytesRead);
				this.offset = this.offset + bytesRead;
			}
			raf.close();
			bis.close();
		} catch (ClientProtocolException e) {
			logger.debug("文件下载 message :" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			logger.debug("文件下载 message :" + e.getMessage());
			e.printStackTrace();
		} finally {
			end.countDown();
		}
	}
}
